﻿#include "circularprogressbar.h"
#include <QPainter>
#include <QPainterPath>

CircularProgressBar::CircularProgressBar(QWidget *parent)
    : QWidget(parent), value(0), foregroundColor(Qt::blue),
      backgroundColor(Qt::lightGray), borderTransparent(true),
      cornerRadius(10), fontSize(14), fontColor(Qt::black), ringWidth(10) {
    // 设置窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground);
}

void CircularProgressBar::setValue(int value) {
    this->value = qBound(0, value, 100); // 限制值在 0-100 之间
    update(); // 触发重绘
}

void CircularProgressBar::setForegroundColor(const QColor &color) {
    this->foregroundColor = color;
    update();
}

void CircularProgressBar::setBackgroundColor(const QColor &color) {
    this->backgroundColor = color;
    update();
}

void CircularProgressBar::setBorderTransparent(bool transparent) {
    this->borderTransparent = transparent;
    update();
}

void CircularProgressBar::setCornerRadius(int radius) {
    this->cornerRadius = radius;
    update();
}

void CircularProgressBar::setFontSize(int size) {
    this->fontSize = size;
    update();
}

void CircularProgressBar::setFontColor(const QColor &color) {
    this->fontColor = color;
    update();
}

void CircularProgressBar::setRingWidth(int width) {
    this->ringWidth = width;
    update();
}

void CircularProgressBar::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 计算圆环的尺寸
    int width = this->width();
    int height = this->height();
    int size = qMin(width, height);
    int penWidth = ringWidth; // 圆环宽度

    // 绘制背景圆环
    QRectF outerRect(penWidth / 2, penWidth / 2, size - penWidth, size - penWidth);
    QPainterPath backgroundPath;
    backgroundPath.addEllipse(outerRect);
    painter.setPen(QPen(backgroundColor, penWidth));
    painter.setBrush(Qt::NoBrush); // 空心圆环
    painter.drawPath(backgroundPath);

    // 绘制前景圆环
    QPainterPath foregroundPath;
    foregroundPath.arcMoveTo(outerRect, 90); // 从顶部开始
    foregroundPath.arcTo(outerRect, 90, -360 * value / 100); // 根据进度绘制圆弧
    painter.setPen(QPen(foregroundColor, penWidth));
    painter.setBrush(Qt::NoBrush); // 空心圆环
    painter.drawPath(foregroundPath);

    // 绘制边框
    if (!borderTransparent) {
        painter.setPen(QPen(Qt::black, penWidth / 2));
        painter.setBrush(Qt::NoBrush);
        painter.drawEllipse(outerRect);
    }

    // 绘制进度文本
    QString text = QString::number(value) + "%";
    QFont font = painter.font();
    font.setPointSize(fontSize);
    painter.setFont(font);
    painter.setPen(fontColor);
    painter.drawText(outerRect, Qt::AlignCenter, text);
}
